package cn.itcast.service.impl;

import cn.itcast.dao.UserDao;
import cn.itcast.dao.impl.UserDaoImpl;
import cn.itcast.domain.PageBean;
import cn.itcast.domain.User;
import cn.itcast.service.UserService;

import java.util.List;
import java.util.Map;

public class UserServiceImpl implements UserService {
    UserDao dao=new UserDaoImpl();
    @Override
    public User login(User user) {
        return dao.findUserByIdAndPassword(user.getId(),user.getPassword());
    }

    @Override
    public PageBean<User> findUserByPage(String _currentPage, String _rows, Map<String, String[]> condition) {
        int currentPage=Integer.parseInt(_currentPage);
        int rows=Integer.parseInt(_rows);

        if (currentPage<=0){
            currentPage=1;
        }

        //1创建空的PageBean对象
        PageBean<User> pb=new PageBean<User>();
        //2设置参数
        /*  pb.setCurrentPage(currentPage);*/
        pb.setRows(rows);
        //3调用dao查询总记录数
        int totalCount=dao.findTotalCount(condition);
        pb.setTotalCount(totalCount);
        //4调用dao查询list集合
        //计算开始的记录索引
        int start=(currentPage-1)*rows;
        List<User> list=dao.findByPage(start,rows,condition);
        pb.setList(list);
        //5计算totalpage,总页码
        int totalPage=(totalCount%rows)==0?totalCount/rows:totalCount/rows+1;

        if(currentPage>totalPage){
            currentPage=totalPage-1;
        }if(currentPage==totalPage){
            currentPage=totalPage;
        }
        pb.setCurrentPage(currentPage);
        pb.setTotalPage(totalPage);
        return pb;
    }

    @Override
    public void updateUser(User user) {
        dao.updateUser(user);
    }

    @Override
    public List<User> findAll() {
        return dao.findAll();
    }

    @Override
    public void addUser(User user) {
        dao.addUser(user);
    }

    @Override
    public User findUserById(String id) {
        return dao.findUserById(Integer.parseInt(id));
    }

    @Override
    public void delSelectedUser(String[] ids) {
        if (ids!=null&&ids.length>0){
            for (String id : ids) {
                dao.delUser(Integer.parseInt(id));
            }
        }
    }

    @Override
    public void delUser(String id) {
        dao.delUser(Integer.parseInt(id));
    }
}
